function update_info(uri,comp_id){
  this.uri = uri;
  this.comp_id = comp_id;
}
function InitIcon(env){
  var icon = new function() {
    this.content_setter = null;
    this.dialog_uri = function(){
      return "/core/dialog/icon/" + env.service_name + "/";
    }
    this.modify_uri = function(){
      return "/xml/modify/" + env.service_name + "/icon/";
    }
    this.update_uri = function(){
      return "/core/service/" + env.service_name + "/?comp=icon"
    }
    this.ShowModifyDialog = function(){
      var self = this;
      env.ui.InfoCollectDialog("ModifyIcon",
        self.dialog_uri(), 
        "form-mdy-icon",
        function(form_obj){
          self.ModifyIcon(form_obj)
        },
        function(){
          YUI().use("node",function(Y){
/**
            var input = Y.one('#form-mdy-icon div.extension-dict-select input');
            Y.Node.getDOMNode(input).ext_onchange = function(path){
              Y.one('#form-mdy-icon img#icon-img-right').set('src',
                '/gallery/image/'+zoyoe.service_name + "/" + path + "/")
            }
**/
            var pathElement = document.getElementsByName('path');
            pathElement[0].ext_onchange = function(path){
              Y.one('#form-mdy-icon img#icon-img-right').set('src',
                '/gallery/image/'+zoyoe.service_name + "/" + path + "/")
            }

            var leftPathElement = document.getElementsByName('leftpath');
            leftPathElement[0].ext_onchange = function(path){
              Y.one('#form-mdy-icon img#icon-img-left').set('src',
                '/gallery/image/'+zoyoe.service_name + "/" + path + "/")
            }
          });
        }
      );
    }
    this.ModifyIcon = function (form_obj){
      var config = {
         method: 'GET',
         form: {id:form_obj}
      }
      var uri = this.modify_uri();
      var request = env.ui.ResponseDialog(uri,config,true
        ,new update_info("/core/service/"+env.service_name+"/?comp=icon","icon"));
    }
  }
  return icon;
}
function InitLayout(env){
  function getSection(node){
    if(node.className=='section-container'){
      var section = null;
      for(var c = node.firstChild;c;c=c.nextSibling){
        if(c.className=='section'){
          env.ALERT(c.id);
          section = c;
          break;
        }
      }
      return section;
    }else{
      return null;
    }
  }
  var layout = new function(){
    this.info = null;
    this.save_uri = function(){
      return "/core/layout/"+env.service_name+'/save/';
    }
    this.template_dialog_uri = function(){
      return "/core/dialog/template/"+env.service_name+'/';
    }
    this.color_dialog_uri = function(){
      return "/core/dialog/color/"+env.service_name+'/';
    }
    this.save_template_uri = function(){
      return "/core/layout/"+env.service_name+'/template/';
    }
    this.build_layout = function(section_name){
      var section_str = [];
      var section = document.getElementById(section_name);
      for(var c = section.firstChild;c;c=c.nextSibling){
        var s = getSection(c);
        if(s){
          section_str.push(s.id);
        }
      }
      return section_str.join(','); 
    }
    this.SaveLayout = function(){
      var config = {
        method: 'GET',
        data:   'left='   + this.build_layout('left-section')
              + "&middle="+ this.build_layout('mid-section')
              + "&right=" + this.build_layout('right-section')
      }
      var request = env.ui.ResponseDialog(this.save_uri(),config,true,null);
        //,new update_info(this.update_uri(),""));
    }
    this.Template = function(){
      var self = this;
      env.ui.InfoCollectDialog("Set Template",
        self.template_dialog_uri(), 
        "form-mdytemplate",
        function(form_obj){
          self.SaveTemplate(form_obj)
        }
      );
    }
    this.Color = function(){
      var self = this;
      env.ui.InfoCollectDialog("Set Color",
        self.color_dialog_uri(), 

        "form-mdycolor",
        function(form_obj){
          self.SaveColor(form_obj)
        }
      );
    }

    this.SaveTemplate = function(form_obj){
      var config = {
        method: 'GET',
        form: {id:form_obj}
      }
      var uri = this.save_template_uri();
      var request = env.ui.GeneralDialogCont(uri,config,true);
    }
  }
  return layout;
}

function InitRoster(env,day){
  function InfoCache(day,select){
    this.day = day;
    this.select = select;
  }
  var roster_comp = new function(){
    this.cache = null;
    this.info_cache = new InfoCache(day,null);
    this.add_roster_uri = function(){
      return "/core/roster/"+env.service_name+'/add/'+this.info_cache.day;
    }
    this.del_roster_uri = function(){
      return "/core/roster/"+env.service_name+'/remove/'+this.info_cache.day;
    }
    this.dialog_add_uri = function(){
      return "/core/dialog/addroster/"+env.service_name+'/'+this.info_cache.day;
    }
    this.update_uri = function(){
      return "/core/service/" + env.service_name +"/?comp=roster&day="+this.info_cache.day;
    }
    this.Select = function(info,ele){
      if(this.cache == ele && ele.className == 'select'){
        ele.className='';
        this.info_cache.select = null;
        this.cache = null;
      }else{
        if(this.cache){
          this.cache.className='';
        }
        ele.className='select';
        this.cache = ele;
        this.info_cache.select = info;
      }
    }
    this.ShowAddDialog = function(){
      var self = this;
      env.ui.InfoCollectDialog("Add Roster",
        self.dialog_add_uri(), 
        "form-addroster",
        function(form_obj){
          self.AddRoster(form_obj)
        }
      );
    }
    this.Update = function(day){
      this.info_cache.day = day;
      this.info_cache.select = null;
      env.Update(new update_info(this.update_uri(),"roster"));
    }
    this.AddRoster = function(form_obj){
      var config = {
        method: 'GET',
        form: {id:form_obj}
      }
      var uri = this.add_roster_uri();
      var request = env.ui.GeneralDialogCont(uri,config,true
        ,new update_info(this.update_uri(),"roster"));
    }
    this.DelRoster = function(gname){
      var config = {
        method: 'GET',
        data:'name='+gname
      }
      var uri = this.del_roster_uri();
      var request = env.ui.ResponseDialog(uri,config,true
        ,new update_info(this.update_uri(),"roster"));
    }
    this.DelSelect = function(){
      if(this.info_cache.select){
        this.DelRoster(this.info_cache.select);
      }
    }
  }
  return roster_comp;
}

function InitRates(env,day){
  function InfoCache(day,select){
    this.day = day;
    this.select = select;
  }
  var rates_comp = new function(){
    this.cache = null;
    this.info_cache = new InfoCache(day,null);
    this.add_rates_uri = function(){
      return "/core/rates/"+env.service_name+'/add/'+this.info_cache.day;
    }
    this.del_rates_uri = function(){
      return "/core/rates/"+env.service_name+'/remove/'+this.info_cache.day;
    }
    this.dialog_add_uri = function(){
      return "/core/dialog/addrates/"+env.service_name+'/'+this.info_cache.day;
    }
    this.update_uri = function(){
      return "/core/service/" + env.service_name +"/?comp=rates&day="+this.info_cache.day;
    }
    this.Select = function(info,ele){
      if(this.cache == ele && ele.className == 'select'){
        ele.className='';
        this.info_cache.select = null;
        this.cache = null;
      }else{
        if(this.cache){
          this.cache.className='';
        }
        ele.className='select';
        this.cache = ele;
        this.info_cache.select = info;
      }
    }
    this.ShowAddDialog = function(){
      var self = this;
      env.ui.InfoCollectDialog("Add Rates",
        self.dialog_add_uri(), 
        "form-addrates",
        function(form_obj){
          self.AddRates(form_obj)
        }
      );
    }
    this.Update = function(day){
      this.info_cache.day = day;
      this.info_cache.select = null;
      env.Update(new update_info(this.update_uri(),"rates"));
    }
    this.AddRates = function(form_obj){
      var config = {
        method: 'GET',
        form: {id:form_obj}
      }
      var uri = this.add_rates_uri();
      var request = env.ui.GeneralDialogCont(uri,config,true
        ,new update_info(this.update_uri(),"rates"));
    }
    this.DelRates = function(gname){
      var config = {
        method: 'GET',
        data:'name='+gname
      }
      var uri = this.del_rates_uri();
      var request = env.ui.ResponseDialog(uri,config,true
        ,new update_info(this.update_uri(),"rates"));
    }
    this.DelSelect = function(){
      if(this.info_cache.select){
        this.DelRates(this.info_cache.select);
      }
    }
  }
  return rates_comp;
}

function InitItems(env,p){
  var item_comp = new function(){
    var path = p;
    this.cache = null;
    this.info_cache = null;
    this.form_name = "xsd-"+path+"-form";

    this.form_uri = function(info){
      //alert("info is ["+ info +"]")
      if(info  && 0 <= info){
        // by mike 
        // return "/xml/dialog/xsd/"+zoyoe.service_name+"/" + path + "/?id="+info;
        return "/xml/dialog_item/xsd/"+zoyoe.service_name+"/" + path + "/?id="+info;
      }else{
        return "/xml/dialog/xsd/"+zoyoe.service_name+"/" + path + "/";
      }
    }
    this.add_uri = function(){
      return "/xml/add/"+env.service_name+'/' + path + '/';
    }
    this.modify_uri = function(id){
      return "/xml/modify/"+env.service_name+'/' + path + '/?id='+id;
    }
    this.delete_uri = function(id){
      return "/xml/remove/"+env.service_name+'/'+id+"/";
    }
 
    this.Select = function(info,ele){
      if(this.cache == ele && ele.className == 'select'){
        ele.className='datalane';
        this.info_cache = null;
        this.cache = null;
        //zoyoe.ui.DisableFrameForm();
      }else{
        if(this.cache){
          this.cache.className='datalane';
        }
        ele.className='select';
        this.cache = ele;
        this.info_cache = info;
        zoyoe.ui.ClearButtons();
        zoyoe.ui.LoadFrameForm(this.form_uri(info));
        if(info == -1){
          zoyoe.ui.LoadButton("Back",function(){
              window.location.href="/core/service/" + env.service_name + "/";
          });
          zoyoe.ui.LoadButton("Add",function(){
            item_comp.AddItem();
          });
        }else{
          zoyoe.ui.LoadButton("Back",function(){
            window.location.href="/core/service/" + env.service_name + "/";
          });
          zoyoe.ui.LoadButton("Save",function(){
            item_comp.ModifyItem();
          });
          zoyoe.ui.LoadButton("Delete",function(){
            item_comp.DeleteItem();
          });
        }
      }
    }
    this.ModifyItem = function(dbid){
      var config = {
        method: 'GET',
        form: {id:item_comp.form_name}
      }
      var uri = this.modify_uri(this.info_cache);
      var request = env.ui.PanelFormSubmit(uri,config,true,path)
    }
    this.AddItem = function(){
      var config = {
        method: 'GET',
        form: {id:item_comp.form_name}
      }
      var uri = this.add_uri();
      var request = env.ui.PanelFormSubmit(uri,config,true,path)
    }
    this.DeleteItem = function(){
      var config = {
         method: 'GET'
      }
      var uri = this.delete_uri(this.info_cache);
      var request = env.ui.PanelFormSubmit(uri,config,true,path)
    }
    this.ShowModifyDialog = function(id){
      var upinfo = new update_info("/core/service/"+env.service_name+"/?comp="+id,id);
      zoyoe.ui.ShowPanel('data',{path:path},upinfo);
    }
  }
  return item_comp;
}

function InitGallery(env){
  function IHandler(name,ele){
    this.name = name;
    this.ele = ele;
  }
  var gallery_comp = new function(){
    this.cache = null;/* The current focus element */
    this.info_cache = null; /* The current Select image item */
    this.showing_gallery = null;
    this.image_handler = [];
    this.content_setter = null;
    this.del_gallery_uri = function(){
      return "/gallery/remove/"+env.service_name +'/';
    }
    this.add_gallery_uri = function(){
      return "/gallery/add/"+env.service_name+'/';
    }
    this.default_gallery_uri = function(){
      return "/core/gallery/"+env.service_name+'/default/';
    }
    this.dialog_add_uri = function(){
      return "/core/dialog/addgallery/"+env.service_name;
    }
    this.dialog_default_uri = function(){
      return "/core/dialog/defaultgallery/"+env.service_name;
    }
    this.ShowModifyDefaultDialog = function(){
      var self = this;
      env.ui.InfoCollectDialog("Default Gallery",
        self.dialog_default_uri(), 
        "form-mdy-default-gallery",
        function(form_obj){
          self.ModifyDefaultGallery(form_obj)
        }
      );
    }
    this.ModifyDefaultGallery = function (form_obj){
      var config = {
         method: 'GET',
         form: {id:form_obj}
      }
      var uri = this.default_gallery_uri();
      var request = env.ui.ResponseDialog(uri,config,true
        ,new update_info("/core/service/"+env.service_name+"/?comp=photoplayer","photoplayer"));
    }
    this.Select = function(name){
      var ele = null;
      for(var i=0;i<this.image_handler.length;i++){
        if(this.image_handler[i].name == name){
          ele = this.image_handler[i].ele;
          this.content_setter("<div class='img-whole'><img onload='zoyoe.ui.Resize();' src='/gallery/image/"
          +env.service_name
          +"/" + this.showing_gallery
          +"/" + name+"'></img></div>"); 
          this.info_cache = name;
          this.cache = ele;
          break;
        }
      }
    }
    this.AddGallery = function(form_obj){
      var config = {
         method: 'GET',
         form: {id:form_obj}
      }
      var uri = this.add_gallery_uri();
      var request = env.ui.GeneralDialogCont(uri,config,true
        ,new update_info("/core/service/"+env.service_name+"/?comp=gallery","gallery"));
    }
    this.DelGallery = function(gname){
      var r=confirm("Are you sure you want to delete the gallery?");
      if (r==false){
        return;
      }
      var config = {
         method: 'GET'
      }
      var uri = this.del_gallery_uri() + gname;
      var request = env.ui.ResponseDialog(uri,config,true
        ,new update_info("/core/service/"+env.service_name+"/"));
    }
    this.GetCode = function(gname){
      var form = zoyoe.ui.PanelLeft().one('form');
      var names = form.all("input");
      var domain = window.location.host;
      var sname = zoyoe.service_name;
      function cliphtml(gname,name){
        var ret = "<a href='http://"+domain+"/gallery/view/"+sname+"/"+gname+"/"+ name+"/'/>";
        ret += "<img src='http://"+domain+"/gallery/image/"+sname+"/"+gname+"/"+name+"/'/><img>";
        ret += "</a>";
        return ret;
      }
      var dialog_msg = "<label>Basic Code</label><textarea>";
      names.each(function(name){
        if(name.get('checked') == true){
          dialog_msg += cliphtml(gname,name.get('value'));
        }
      });
      dialog_msg += '</textarea>';
      dialog_msg += "<label style='margin-top:15px;'>Gallery Code</label><textarea>";
      dialog_msg += 'not implemented</textarea>';
      zoyoe.ui.GeneralAlert(dialog_msg,'basic code',null,false);
    }
    this.ShowAddDialog = function(){
      var self = this;
      env.ui.InfoCollectDialog("Add Gallery",
        self.dialog_add_uri(), 
        "form-addgallery",
        function(form_obj){
          self.AddGallery(form_obj)
        }
        ,null,"/wiki/addgallery.html"
      );
    }
    this.ManageGallery = function(gname,name_list,setter){
      this.showing_gallery = gname;
      this.content_setter = setter;
      this.image_handler = [];
      for(var i=0;i<name_list.length;i++){
        this.image_handler.push(new IHandler(name_list[i]))
      }
      if(name_list.length == 0){
      this.content_setter("<h1>Oops!!! This Gallery is Empty at the Moment. </h1>"
        + "<p>For information about how to manage the gallery please visit our help page</p>"
        + "<br/> <p>To add a new image click button 'update new image'</p>"
        + "<br/> <p>To delete this gallery click button 'delete this gallery'</p>")
      }
    }
    this.AddImg = function(iname,usetmp){
      function overlap(iname,handlers){
        if(iname){
          for(var i=0;i<handlers.length;i++){
            if(handlers[i].name == iname){
              return true;
            }
          }
          return false;
        }else{
          return true;
        }
      }
      if(this.showing_gallery == null){
      }else{
        var name = "newimg";
        var count = 1;
        var iname = iname;
        while(overlap(iname,this.image_handler)){
          iname = name + count;
          count += 1;
        }
        var ht = "<iframe frameborder='0' onload=\"zoyoe.comps['GALLERY'].AddImgProgress(this,'" + this.info_cache + "')\" src = '/core/dialog/res/"
                + env.service_name
                + "/" + this.showing_gallery
                + "/"+iname+"/?action=add' ></iframe>" 
        if(usetmp){
          ht += "&usetmp=true"
        }
        ht += "' ></iframe>";
        this.content_setter(ht);
      }
    }
    this.ModifyImg = function(usetmp){
      if(this.showing_gallery == null){
      }else if(this.info_cache == null){
      }else{
        var ht = "<iframe frameborder='0' onload=\"zoyoe.comps['GALLERY'].ModifyImgProgress(this,'" + this.info_cache + "')\" src = '/core/dialog/res/"
                + env.service_name
                + "/" + this.showing_gallery
                + "/" + (this.info_cache) +"/?action=modify'></iframe>";
        if(usetmp){
          ht += "&usetmp=true"
        }
        ht += "' ></iframe>"
        this.content_setter(ht);
      }
    }
    this.DeleteImg = function(gname, name){
      zoyoe.uploader.Delete(gname, name);
    }
    this.AddImgProgress = function(iframe,iname){
      var doc = iframe.contentWindow || iframe.contentDocument;
      var SUCC = doc.document.getElementsByTagName('SUCC');
      if(SUCC.length == 1){
        env.timestamp = SUCC[0].getAttribute('timestamp');
        //Convention Used Here
        var url = (SUCC[0].getElementsByTagName('RESURL')[0].firstChild.data);
        this.content_setter("<img src='" + url + "'></img>"); 
        //Update Component
        env.ui.HidePanel();
        env.ui.ShowPanel('gallery',[this.showing_gallery],'gallery');
      }
    }
    this.ModifyImgProgress = function(iframe,iname){
      var doc = iframe.contentWindow || iframe.contentDocument;
      var SUCC = doc.document.getElementsByTagName('SUCC');
      if(SUCC.length == 1){
        env.timestamp = SUCC[0].getAttribute('timestamp');
        var url = (SUCC[0].getElementsByTagName('RESURL')[0].firstChild.data);
        this.content_setter("<img src='" + url + "'></img>"); 
        env.ui.HidePanel();
        env.ui.ShowPanel('gallery',[this.showing_gallery],'gallery');
      }
    }
  }
  return gallery_comp;
}
function InitBasicInfo(zo){
  // alert("init basic info");
  var env = zo;  
  var basic_info = new function(){
    this.mdy_dialog_uri = "/core/dialog/mdyservice/" + zoyoe.service_name + "/";
    this.mdy_dialog_uri = "/core/dialog/mdyservice/" + zoyoe.service_name + "/";
    this.mdy_service_uri = "/core/data/mdyservice/";
    this.ShowModifyServiceDialog = function(){
      // alert("in show modify service dialog");
      var uri = this.mdy_service_uri;
      function ModifyService(form_obj){
        // alert("before update basic information");
        var days = new Array();
/*
        if(form_obj.Sun.checked){days.push("Sun");}
        if(form_obj.Mon.checked){days.push("Mon");}
        if(form_obj.Tue.checked){days.push("Tue");}
        if(form_obj.Wed.checked){days.push("Wed");}
        if(form_obj.Thu.checked){days.push("Thu");}
        if(form_obj.Fri.checked){days.push("Fri");}
        if(form_obj.Sat.checked){days.push("Sat");}
*/
        days.push("Sun");
        days.push("Mon");
        days.push("Tue");
        days.push("Wed");
        days.push("Thu");
        days.push("Fri");
        days.push("Sat");
        zoyoe.ALERT(days.join(','));
        var mdy_service_config = {
          method: 'POST',
          data:"&days="+days.join(','),
          form: {id:form_obj}
        }
        zoyoe.ui.GeneralDialogCont(uri+zoyoe.service_name+"/",mdy_service_config,true,null);
      }
      env.ui.InfoCollectDialog("Basic Information",
      this.mdy_dialog_uri,"form-mdyservice",ModifyService,null,'/wiki/modifyservice.html');
    }
  }
  return basic_info;
}

function InitDescription(zo){
  // alert("init description");
  var env = zo;  
  var description = new function(){
    // this.mdy_dialog_uri = "/core/dialog/mdyservice/" + zoyoe.service_name + "/";
    this.mdy_desc_dialog_uri = "/core/dialog/mdydescription/" + zoyoe.service_name + "/";
    this.mdy_desc_uri = "/core/data/mdydescription/";
    this.ShowModifyDescDialog = function(){
      // alert("before update Description information ");
      var uri = this.mdy_desc_uri;

      function ModifyDescription(form_obj){
        // alert("in modify description function");
        var days = new Array();

        days.push("Sun");
        days.push("Mon");
        days.push("Tue");
        days.push("Wed");
        days.push("Thu");
        days.push("Fri");
        days.push("Sat");
        zoyoe.ALERT(days.join(','));
        var mdy_service_config = {
          method: 'POST',
          data:"&days="+days.join(','),
          form: {id:form_obj} 
        }
        zoyoe.ui.GeneralDialogCont(uri+zoyoe.service_name+"/",mdy_service_config,true,null);
      }


      env.ui.InfoCollectDialog("Description",
      this.mdy_desc_dialog_uri,"form-mdydescription",ModifyDescription,null,'/wiki/modifydescription.html');
    }
  }
  return description;
}

function InitAdmin(zo){
  var env = zo;
  var admin = new function(){
    this.login_uri = "/core/user/login/";
    this.register_uri = "/core/user/register/";
    this.change_pwd_uri = "/core/user/changepwd/";
    this.addserv_dialog_uri = "/core/dialog/addservice/";
    this.login_dialog_uri = "/core/dialog/login/";
    this.register_dialog_uri = "/core/dialog/register/";
    this.pwd_dialog_uri = "/core/dialog/changepwd/";
    this.aboutus_dialog_uri = "/core/dialog/aboutus/";
    this.del_uri = function(sname){
      return "/core/data/delservice/"+sname+"/";
    }
    this.reset_uri = function(sname){
      return "/core/data/reset/"+sname+"/";
    }
    this.enable_forum_uri = function(sname){
      return "/glue/forum-activate/"+sname+"/";
    }
    this.add_collect_uri = "/glue/collect/add/"; 
    this.del_collect_uri = "/glue/collect/del/"; 
    this.DeleteService = function(sname){
      env.ui.GeneralAlert("You are trying to delete this service !",'Confirm Your Decision',function(){
      env.ui.ResponseDialog(admin.del_uri(sname),config,true,null);
      },false);
    }
    this.ResetService = function(sname){
      env.ui.GeneralAlert("You are trying to reset this service !",'Confirm Your Decision',function(){
      env.ui.ResponseDialog(admin.reset_uri(sname),config,true,null);
      },false);
    }
    this.EnableForum = function(sname){
      env.ui.GeneralAlert("You are trying to enable forum for this service!",'Confirm Your Decision',function(){
      env.ui.ResponseDialog(admin.enable_forum_uri(sname),config,true,null);
      },false);
    }
    this.RegisterCallback = function(redirect_uri){
      var uri = this.register_uri;
      var update = null;
      function Register(form_obj){
        if(form_obj.confirm.value != form_obj.password.value){
          zoyoe.ui.ShowDialog(zoyoe.ui.dialog_title,false);
          zoyoe.ui.BuildErrorMsg("! Password not confirmed.")
          return;
        }
        var register_config = {
          method: 'GET',
          form: {id:form_obj}
        }
        if(redirect_uri){
          update = new function(){
            this.uri = redirect_uri;
          }
        }
        zoyoe.ui.GeneralDialogCont(uri,register_config,true,update);
      }
      return Register;
    }
 
    this.ShowRegisterDialog = function(){
      env.ui.InfoCollectDialog("Register",
      this.register_dialog_uri,"form-register",admin.RegisterCallback(),null,'/wiki/register.html');
    }

    this.ChangePWDCallback = function(redirect_uri){
      var uri = this.change_pwd_uri;
      var update = null;
      function Register(form_obj){
        if(form_obj.confirm.value != form_obj.password.value){
          zoyoe.ui.ShowDialog(zoyoe.ui.dialog_title,false);
          zoyoe.ui.BuildErrorMsg("! Password not confirmed.")
          return;
        }
        var register_config = {
          method: 'GET',
          form: {id:form_obj}
        }
        if(redirect_uri){
          update = new function(){
            this.uri = redirect_uri;
          }
        }
        zoyoe.ui.GeneralDialogCont(uri,register_config,true,update);
      }
      return Register;
    }
 
    this.ShowChangePWDDialog = function(){
      env.ui.InfoCollectDialog("Change Password",
      this.pwd_dialog_uri,"form-change-pwd",admin.ChangePWDCallback());
    }
    this.LoginCallback = function(cb){
      var uri = this.login_uri;
      function Login(form_obj){
        var login_config = {
          method: 'GET',
          form: {id:form_obj}
        }
        zoyoe.ui.GeneralDialogCont(uri,login_config,true);
      }
      return Login;
    }
    this.ShowLoginDialog= function(){
      env.ui.InfoCollectDialog("Login",
      this.login_dialog_uri,"form-login",admin.LoginCallback(),null,'/wiki/login.html');
    }
    this.ShowAboutUsDialog= function(){
      env.ui.InfoCollectDialog("About Us",
      this.aboutus_dialog_uri,"form-aboutus",null,null,'/wiki/aboutus.html');
    }
    this.ShowWarningDialog= function(){
      env.ui.InfoCollectWarningDialog("",
      null,null,null,null,'/wiki/warning.html');
    }
    this.ShowAddServiceDialog = function(){
      env.ui.InfoCollectDialog("Publish Club",this.addserv_dialog_uri,"form-addservice",AddService,null,'/wiki/publish.html');
    }
    this.Collect = function(){
      var collect_config = {
        method: 'POST',
        data:'name='+zoyoe.service_name
      }
      var request = zoyoe.ui.ResponseDialog(this.add_collect_uri,
        collect_config,true,null);
    }
    this.CollectDelete = function(service_name){
      var collect_config = {
        method: 'POST',
        data:'name='+service_name
      }
      var request = zoyoe.ui.ResponseDialog(this.del_collect_uri,
        collect_config,true,null);
    }
    function Reload(){
      if(document.forms['reload']){
        document.forms['reload'].submit();
      }else{
        zoyoe.ALERT('Try alternative Reload Function');
        location.reload(true);
      }
    }
    this.Logout = function(){
      var logout_uri = "/core/user/logout/";
      YUI().use("io-form",function(Y){
        uri = logout_uri;
        var logout_config = {
          method: 'GET'
        }
        function complete(id,o,args){
          Reload();
        }
        Y.on('io:complete',complete);
        var request = Y.io(logout_uri,logout_config);
      });
    }
  }
  return admin;
}

function AddService(form_obj){
  zoyoe.ui.ShowDialog(zoyoe.ui.dialog_title,true);
  var map_comp = zoyoe.map;/*Convention*/
  var script = document.createElement("script");
  script.setAttribute("type","text/javascript"); 
  if (form_obj.address.value.length != 0){
    script.setAttribute("src",map_comp.SearchUri(form_obj.address.value+',Australia')
    +"&jsonp=AddServiceJSON");    
  }
  else{
    zoyoe.ui.BuildErrorMsg('Please enter address !!');
  }
  document.body.appendChild(script);
}
function BuildResultAddress(form_obj,result){
  if(result.resourceSets){
    if(result.resourceSets[0].estimatedTotal == 0){
      zoyoe.ui.BuildErrorMsg('Address Not Found !!');
      return null;
    }
    else if(result.resourceSets[0].estimatedTotal == 1){
      var resources = result.resourceSets[0].resources;
      if(resources[0].address.formattedAddress == "New South Wales"){
        zoyoe.ui.BuildErrorMsg("Address Not Found !!");
        return null;
      }else if(resources.length == 1){
        zoyoe.ALERT(resources[0].address.formattedAddress);
        form_obj.address.value = resources[0].address.formattedAddress; 
        var c = resources[0].point.coordinates;
        return c;
      }else{
        zoyoe.ui.BuildErrorMsg('Ambiguious Address,Please Make It Clear !!');
        return null;
      }
    }
    else{
      var resources = result.resourceSets[0].resources;
      zoyoe.ui.BuildErrorMsg('Multi Address Found,Please Make It Clear !!');
      return null;
    }
  }
}

function AddServiceJSON(result){
  var form_obj = document.getElementById(zoyoe.ui.dialog_name);
  var days = new Array();
  var add_service_uri = "/core/data/addservice/";
  if(result.resourceSets){
    if(result.resourceSets[0].estimatedTotal == 0){
      zoyoe.ui.BuildErrorMsg('Address Not Found !!');
    }
    else if(result.resourceSets[0].estimatedTotal == 1){
      var resources = result.resourceSets[0].resources;
      if(resources[0].address.formattedAddress == "New South Wales"){
        zoyoe.ui.BuildErrorMsg("Address Not Found !!");
      }else if(resources.length == 1){
        zoyoe.ALERT(resources[0].address.formattedAddress);
        //form_obj.address.value = resources[0].address.formattedAddress;
        form_obj.local.value = resources[0].address.locality;
        
        /*if(form_obj.Sun.checked){days.push("Sun");}
        if(form_obj.Mon.checked){days.push("Mon");}
        if(form_obj.Tue.checked){days.push("Tue");}
        if(form_obj.Wed.checked){days.push("Wed");}
        if(form_obj.Thu.checked){days.push("Thu");}
        if(form_obj.Fri.checked){days.push("Fri");}
        if(form_obj.Sat.checked){days.push("Sat");}*/
        days.push("Sun");
        days.push("Mon");
        days.push("Tue");
        days.push("Wed");
        days.push("Thu");
        days.push("Fri");
        days.push("Sat");
        var c = resources[0].point.coordinates;
        zoyoe.ALERT(days.join(','));
        var add_service_config = {
          method: 'POST',
          data:'latitude='+c[0]+"&longitude="+c[1]+"&days="+days.join(','),
          form: {id:form_obj}
        }
        zoyoe.ui.HideDialog();
        zoyoe.ui.GeneralDialogCont(add_service_uri,add_service_config,
          true,function(dom){
            var ss = dom.documentElement.getElementsByTagName('SERVICE');
            var service = new Service(ss[0]);
            window.location.href = "/core/service/"+service.name;
          });
      }else{
        zoyoe.ui.BuildErrorMsg('Ambiguious Address,Please Make It Clear !!');
      }
    }
    else{
      var resources = result.resourceSets[0].resources;
      var select = "<form name='select-address'><select name='select' onchange=\"document.getElementById('address-input').value = this.options[this.selectedIndex].value\"><option value=''>---</option>";
      for(var i = 0; i < resources.length; i++){
        var option_val = resources[i].address.formattedAddress;
        select += "<option value='" + option_val + "' id='sel'>" + option_val + "</option>";
      }
      select += "</select></form>";
      zoyoe.ui.BuildErrorMsg('Multi Address Found,Please Make It Clear !!' + select);
    }
  }
}

function InitSearch(opt_ele_container,option_path,validate,invalidate){
  function NonePadding(str){
    if(str){return str;}
    else{return "";}
  }

  function refineAddress(address){
    address = doRefine(address, ", Australia");
    address = doRefine(address, ",Australia");
    address = doRefine(address, ", NSW");
    address = doRefine(address, ",NSW");
    return address;
  }

  function doRefine(address, refiner) {
    if(address.indexOf(refiner) != -1) {
      address = address.replace(refiner, "");
    }
    return address;
  }
  var search = new function(){
    var self = this;
    var filter = {LOCATION:{x:0,y:0},
                   TARGET:'general',
                   MAIN:'',
                   STYPE:'',
                   LOCAL:'',
                   NATION:'',
                   RADIUS:1,
                   PRICE:{MIN:0,MAX:9876},
                   AGE:''
                  }
    this.MarkValidate = validate;
    this.MarkInvalidate = invalidate;
    this.option = option_path;
    this.optcontainer = opt_ele_container;
    this.SetPreference = function(path,idx){
      self.option = path;
      filter['TARGET'] = path;
      if(!this.optcontainer){return;}
      self.optcontainer.all('a').set('className','');
      self.optcontainer.all('a').item(idx).set('className','select');
    }
    this.AutoComplete = function(searchStr){
      /* comment by mike for testing , in product env ,we should uncomment it
      if(zoyoe.map && this.option == "address"){
        zoyoe.map.TargetPlace(searchStr,"AutoCompJSON");
      }else{
      }*/
      this.option="address";
     
      zoyoe.map.TargetPlace(searchStr,"AutoCompJSON");
    }

    this.PreSearch = function(){
      // all search based on the address
      // alert("before search by address");
      var iphone = document.getElementById('iphone-warpper');
      if (iphone) {
        this.SearchByAddressForMobile();
      }else{
        this.SearchByAddress();
      }

      /*
      if(this.option == "address"){
        this.SearchByAddress();
      }else{
        this.NormalSearch();
      }
      */
      return false;
    }
    this.TargetType = function(type,keep){
      if(keep){
        filter.STYPE = type;
      }else{
        filter = {LOCATION:{x:0,y:0},
                 TARGET:'general',
                 MAIN:'',
                 STYPE:type,
                 LOCAL:'',
                 NATION:'',
                 RADIUS:1,
                 PRICE:{MIN:0,MAX:9876},
                 AGE:''
                }
      
      }
      this.PerformSearch();
    }
    this.TargetLocation = function(local,keep){
      if(keep){
        filter.LOCAL = local;
      }else{
        filter = {LOCATION:{x:0,y:0},
                 TARGET:'general',
                 MAIN:'',
                 STYPE:'',
                 LOCAL:local,
                 NATION:'',
                 RADIUS:1,
                 PRICE:{MIN:0,MAX:9876},
                 AGE:''
                }
      
      }
      this.PerformSearch();
    }
    this.GetFilter = function(){
      return filter;
    }
    this.PerformSearch = function(){
    YUI().use("json-stringify","node",function (Y) {
      var filterStr = Y.JSON.stringify(filter);
      window.location.href = "/core/services/?"+"filter=" + filterStr;
    });
    }
    this.NormalSearch = function(){
    YUI().use("json-stringify","node",function (Y) {
      var searchStr = "";

      if (Y.one("#main-search-bar input") != null) {
        if (Y.Node.getDOMNode(Y.one("#main-search-bar input")) != null) {
          searchStr = Y.Node.getDOMNode(Y.one("#main-search-bar input")).value;
        } else {
          // search more in the map page
          searchStr = "Please enter shop's name";
        }
      } else { 
          searchStr = "Please enter your location or postcode";
      }
      var patten = new RegExp("[a-zA-Z0-9]+");
      if(patten.test(searchStr) == false){
        self.MarkInvalidate("Invalid Query String");
        return;/* early return here, since the search string is empty */
      }
      if (searchStr == "Please enter shop's name"
       || searchStr == "Please enter girl's name"
       || searchStr == "Please enter your location or postcode") {
        searchStr = "";
      }
      filter.MAIN = searchStr;

      if (Y.one("#service-type input") != null) {
          filter.STYPE = NonePadding(Y.Node.getDOMNode(Y.one("#service-type input")).value);
      } else {
          filter.STYPE = "";
      }
      if (Y.one("#service-local input") != null) {
          filter.LOCAL = NonePadding(Y.Node.getDOMNode(Y.one("#service-local input")).value);
      } else {
          filter.LOCAL = "";
      }

      if (Y.one("#nationality input") != null) {
          filter.NATION = NonePadding(Y.Node.getDOMNode(Y.one("#nationality input")).value);
      } else {
          filter.NATION = "";
      }

      if (Y.one("#price input") != null) {
          var price_str = NonePadding(Y.Node.getDOMNode(Y.one("#price input")).value);
          if (price_str != "Any") {
            var priceReg = /(\d+)-(\d+)/;
            filter.PRICE.MIN = price_str.replace(priceReg, "$1");
            filter.PRICE.MAX = price_str.replace(priceReg, "$2");
          }
      } else {
          filter.PRICE = "";
      }

      delete filter.RADIUS;
      zoyoe.search.PerformSearch();
    });
    }
    this.SearchByAddress = function(){
      // alert("in search by address ********");
    YUI().use("json-stringify","node",function (Y) {
      var searchStr = "";
      var orgSearchStr = "";

      if (Y.one("#main-search-bar input") != null) {
        searchStr = Y.Node.getDOMNode(Y.one("#main-search-bar input")).value;
        orgSearchStr = searchStr;
      } else {
        searchStr = "Please enter your location or postcode";
      }
      var patten = new RegExp("[a-zA-Z0-9]+");
      if(patten.test(searchStr) == false){
        self.MarkInvalidate("Invalid Query String");
        return;/* early return here, since the search string is empty */
      }
      if (searchStr == "Please enter your location or postcode") {
        // use a default location
        searchStr = "Sydney";
      }
      searchStr = refineAddress(searchStr);//remove 'Australia' or 'NSW'
      filter.STYPE = NonePadding(Y.Node.getDOMNode(Y.one("#service-type input")).value);
      if (Y.one("#service-local") != null) {
          filter.LOCAL = NonePadding(Y.Node.getDOMNode(Y.one("#service-local input")).value);
      }  else {
          filter.LOCAL = "";
      }
      if (Y.one("#radius input") != null) {
          var radius_str = Y.Node.getDOMNode(Y.one("#radius input")).value;
          var radiusReg = /\D*(\d+)\D*/;
          radius_str = radius_str.replace(radiusReg, "$1");
          if (radius_str != null && radius_str != "") {
              filter.RADIUS = NonePadding(parseInt(radius_str));
          } else {
              filter.RADIUS = "40";
          }
      } else {
          filter.RADIUS = "40";
      }
      
      if (Y.one("#nationality input") != null) {
          filter.NATION = NonePadding(Y.Node.getDOMNode(Y.one("#nationality input")).value);
      } else {
          filter.NATION = "";
      }

      if (Y.one("#price input") != null) {
          var price_str = NonePadding(Y.Node.getDOMNode(Y.one("#price input")).value);
          if (price_str != "Any") {
            var priceReg = /\D*(\d+)/;
            filter.PRICE.MIN = price_str.replace(priceReg, "$1");
            filter.PRICE.MAX = "5000";
            /*
            var priceReg = /(\d+)-(\d+)/;
            filter.PRICE.MIN = price_str.replace(priceReg, "$1");
            filter.PRICE.MAX = price_str.replace(priceReg, "$2");
            */
          }
      }

      if (Y.one("#age input") != null) {
          filter.AGE = NonePadding(Y.Node.getDOMNode(Y.one("#age input")).value);
          if (filter.AGE == "Any") {
              filter.AGE = "";
          }
      } else {
          filter.AGE = "";
      }

      if (orgSearchStr != null && orgSearchStr != "") {
          filter.OAD = orgSearchStr;
      } else {
          filter.OAD = "";
      }
      
      var filterStr = Y.JSON.stringify(filter);
      zoyoe.ALERT(searchStr);
      zoyoe.map.TargetPlace(searchStr,"Search")
    });
    }


    /* Search by address for mobile ,changed by mike in 20121107*/
    this.SearchByAddressForMobile = function(){
      YUI().use("json-stringify","node",function (Y) {
        var searchStr = "";
        var orgSearchStr = "";

        if (Y.one("#main-search-bar input") != null) {
          searchStr = Y.Node.getDOMNode(Y.one("#main-search-bar input")).value;
          orgSearchStr = searchStr;
        } else {
          searchStr = "Please enter your location or postcode";
        }
        var patten = new RegExp("[a-zA-Z0-9]+");
        if(patten.test(searchStr) == false){
          self.MarkInvalidate("Invalid Query String");
          return;/* early return here, since the search string is empty */
        }
        if (searchStr == "Please enter your location or postcode") {
          // use a default location
          searchStr = "Sydney";
        }
        searchStr = refineAddress(searchStr);//remove 'Australia' or 'NSW'
        filter.STYPE = NonePadding(Y.Node.getDOMNode(Y.one("#service-type input")).value);
        if (Y.one("#service-local") != null) {
            filter.LOCAL = NonePadding(Y.Node.getDOMNode(Y.one("#service-local input")).value);
        }  else {
            filter.LOCAL = "";
        }

        if (Y.one("#distance_value") != null) {
          filter.RADIUS = Y.Node.getDOMNode(Y.one("#distance_value")).value;
          if(filter.RADIUS == '')
            filter.RADIUS = "6";
        } else {
          filter.RADIUS = "40";
        }

        filter.NATION = "Asia,Australia,Europe,China,Korea,Japan,Viet Nam,Thailand,Malaysia,Singapore,Philippines,America,Africa";

        if (Y.one("#price_value") != null) {
          filter.PRICE.MIN = Y.Node.getDOMNode(Y.one("#price_value")).value;
          if(filter.PRICE.MIN == '')
            filter.PRICE.MIN = "0";
          filter.PRICE.MAX = "5000";
        }

        filter.AGE = "";

        if (orgSearchStr != null && orgSearchStr != "") {
            filter.OAD = orgSearchStr;
        } else {
            filter.OAD = "";
        }
        
        var filterStr = Y.JSON.stringify(filter);
        zoyoe.ALERT(searchStr);
        // alert(filterStr);
        zoyoe.map.TargetPlace(searchStr,"SearchForMobile")
      });
    }

  };
  return search;
}




